/*
 * Copyright By Peak3
 * Copyright By c336bf6ff03a756989bb456b5b5e3271228d43ed38461eb5cb5755d17a2fc9b8
 * All rights reserved.
 *
 * If you are not the intended user, you are hereby notified that any use, disclosure, copying, printing, forwarding or
 * dissemination of this property is strictly prohibited. If you have got this file in error, delete it from your system.
 */

package com.vv.tools.common.util;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.builder.CustomFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.vv.tools.common.support.BaseModel;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

/**
 * 代码生成
 *
 * @author liwen
 */
public class CodeGenerator {

    private static final String URL =
        "jdbc:mysql://awschina-nx-genesis-tenant-dev1-rds-01.crag5sximeqt.rds.cn-northwest-1.amazonaws.com.cn:3306/carro_bot_00";

    private static final String USERNAME = "genesis_dev1_rw";

    private static final String PASSWORD = "43upKSSeGau7HBRi";

    private static final String BASE_PATH = "com.vv.tools";

    /**
     * mybatis-plus代码生成器
     */
    public static void main(String[] args) {
        // 模块
        String module = "sys";
        // 生成表
        String table = "sys_captcha,sys_log,sys_menu,sys_role,sys_role_menu,sys_user,sys_user_role";
        // run
        run(module, table);
    }


    public static void run(String module, String table) {
        Path finalProjectPath = Paths.get(System.getProperty("user.dir"));
        System.out.println(finalProjectPath);
        FastAutoGenerator.create(URL, USERNAME, PASSWORD)
            .globalConfig(builder -> builder
                .author("vv") // 作者
                .outputDir(finalProjectPath + "/src/main/java") // 指定输出目录
                .disableOpenDir() // 禁止打开输出目录
            )
            .dataSourceConfig(builder ->
                builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                    int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                    if (typeCode == Types.SMALLINT || typeCode == Types.TINYINT) {
                        // 自定义类型转换
                        return DbColumnType.INTEGER;
                    }
                    return typeRegistry.getColumnType(metaInfo);
                })
            )
            .packageConfig(builder -> builder
                .parent(BASE_PATH + ".modules")  // 父包
                .moduleName(module)     // 模块
                .controller("controller")   // controller
                .service("service")  // service
                .serviceImpl("service.impl") // service实现
                .entity("entity") // entity
                .mapper("dao")  // mapper
                .pathInfo(Map.of(
                    OutputFile.xml, finalProjectPath + "/src/main/resources/mapper/" + module // xml文件
                ))
            )
            .injectionConfig(injectConfig -> {
                Map<String, Object> customMap = new HashMap<>();
                customMap.put("dtoPackage", BASE_PATH + ".modules." + module + ".model");
                customMap.put("convertPackage", BASE_PATH + ".modules." + module + ".converter");
                injectConfig.customMap(customMap); //注入自定义属性
                injectConfig.customFile(new CustomFile.Builder()
                    .fileName("DTO.java") //文件名称
                    .templatePath("/ftl/entityDTO.java.ftl") //指定生成模板路径
                    .packageName("model") //包名,自3.5.10开始,可通过在package里面获取自定义包全路径,低版本下无法获取,示例:package.entityDTO
                    .build());
                injectConfig.customFile(new CustomFile.Builder()
                    .fileName("Convert.java") //文件名称
                    .templatePath("/ftl/entityConvert.java.ftl") //指定生成模板路径
                    .packageName("converter") //包名,自3.5.10开始,可通过在package里面获取自定义包全路径,低版本下无法获取,示例:package.entityDTO
                    .build());
            })
            .strategyConfig(builder -> builder
                .addInclude(table)  // 导出的表
                .addTablePrefix("sys_")  // 表前缀
                // entity builder
                .entityBuilder()  // 启用builder
                .superClass(BaseModel.class) // 父类
                .enableFileOverride() // 覆盖已生成文件
                .enableLombok()  // 启用lombok
                .addIgnoreColumns("gmt_created", "gmt_modified", "is_deleted") // 添加忽略字段
                .disableSerialVersionUID()  // 禁用生成 serialVersionUID
                .enableRemoveIsPrefix()  // 开启 Boolean 类型字段移除 is 前缀
                .enableTableFieldAnnotation() // 启用字段注解
                // service builder
                .serviceBuilder()
                .formatServiceFileName("%sService")
                .enableFileOverride()
                // mapper builder
                .mapperBuilder()
                .enableBaseResultMap()
                .enableFileOverride()
            )
            .templateEngine(new FreemarkerTemplateEngine())
            .execute();
    }

}
